package com.tech.koufu.ui.activity.menu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.RequestQueue;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.lidroid.xutils.bitmap.PauseOnScrollListener;
import com.tech.koufu.MyApplication;
import com.tech.koufu.R;
import com.tech.koufu.action.RequestQueueSingleton;
import com.tech.koufu.model.ChooseStock; 
import com.tech.koufu.tools.CookieStringRequest;
import com.tech.koufu.tools.KouFuTools;
import com.tech.koufu.tools.Statics;
import com.tech.koufu.ui.activity.MarketDeatilActivity; 
import com.tech.koufu.ui.adapter.ChooseStockAdapter; 

import extras.com.handmark.pulltorefresh.library.PullToRefreshBase;
import extras.com.handmark.pulltorefresh.library.PullToRefreshListView;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 我的自选股
 * @name: MyChooseStockActivity 
 * @description: 
 * @date 2015年7月8日 下午3:10:25
 *  
 */
public class MyChooseStockActivity extends Activity implements Callback ,OnClickListener{
	public static final String TAG = MyChooseStockActivity.class.getName();
	private int page = 1; 
	
	private ListView actualListView;
	private PullToRefreshListView mPullToRefreshListView;
//	private RequestQueue mQueue; 
	private MyApplication myApp;
//	private CookieStringRequest stringRequest;
//	private StringRequest strRequest;
	private ChooseStockAdapter mAdapter;
	public ArrayList<ChooseStock> mDatas;
	private Handler mHandler;
	private String ncode;
	private Context context;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) { 
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mychoosestock); 
		context = getApplicationContext();
		initView();
		initData();
	}
	
	@Override
	protected void onResume() { 
		super.onResume();
	}
	
	private void initView(){
		TextView title = (TextView) findViewById(R.id.tv_title); 
		title.setText(R.string.menu_myChooseStock);
		title.setVisibility(View.VISIBLE);
		ImageView ivBack = (ImageView) findViewById(R.id.img_callback);
		ivBack.setVisibility(View.VISIBLE);
		ivBack.setOnClickListener(this);
		
//		mQueue = Volley.newRequestQueue(getApplicationContext());
		myApp = (MyApplication)getApplication();
		mPullToRefreshListView = (PullToRefreshListView)findViewById(R.id.lv_mystocks);
		actualListView = mPullToRefreshListView.getRefreshableView(); 
		registerForContextMenu(actualListView);
		
		mAdapter = new ChooseStockAdapter(getApplicationContext());
		actualListView.setAdapter(mAdapter);
		actualListView.setOnItemClickListener(itemClick);
		mAdapter.userId = myApp.getDigitalid();
//		mAdapter.mQueue = mQueue;
	}
	
	private void initData(){
		mHandler = new Handler(this);
		mDatas = new ArrayList<ChooseStock>();
		mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) { 
				Mode mode = mPullToRefreshListView.getCurrentMode(); 
		        if(mode == Mode.PULL_FROM_START) { 
		        	mDatas.clear();
		        	page=1; 
		        }else {
		        	page++; 
		        }  
		        loadMyChooseStocks();
			}
		}); 
		Message msg = Message.obtain();
		msg.what = 3;
		mHandler.sendMessageDelayed(msg, 50); 
		mPullToRefreshListView.setMode(Mode.BOTH);
	}
	
	private void loadMyChooseStocks(){
		String url = Statics.URL_PHP + Statics.IF_myZixuangu;
		
		CookieStringRequest stringRequest = new CookieStringRequest(Method.POST, url, new Listener<String>() {

			@Override
			public void onResponse(String response) {
				Log.v(TAG, response);
				// ﻿{"status":0,"info":"","data":[{"stock_code":"603085","stock_name":"\u5929\u6210\u81ea\u63a7","stock_type":"","add_time":"2015.07.08","ROW_NUMBER":"1"}]}

				if(!TextUtils.isEmpty(response)){
					try {
						JSONObject obj = new JSONObject(response);
						if(obj.getInt("status") == 0){
							JSONArray arry = obj.optJSONArray("data");
						 
							if(arry!=null){
								StringBuilder codeBuilder = new StringBuilder();
								for(int i=0;i<arry.length();i++){
									JSONObject jo = arry.optJSONObject(i);
									ChooseStock cs = new ChooseStock(jo);
									mDatas.add(cs);
									codeBuilder.append(KouFuTools.getNcode(cs.stockcode)).append(",");
								}
								ncode = codeBuilder.toString();
								if(!TextUtils.isEmpty(ncode)){
									loadBinStock();
								}
							}else{
								page--;
							}
						}else{
							 
						}
					} catch (JSONException e) { 
						e.printStackTrace();
					}

				}
			
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) { 
				mPullToRefreshListView.onRefreshComplete();
			}			
		}){
			@Override
			protected Map<String, String> getParams() throws AuthFailureError { 
				Map<String, String> params = new HashMap<String, String>(); 
				params.put("page", page+"");    
				params.put("userID", myApp.getDigitalid()); 
				return params;
			}
		};
		
		stringRequest.setHeader(myApp.phpsessid);
		stringRequest.setTag(TAG);
		RequestQueueSingleton.getInstance(context).addToRequestQueue(stringRequest);
	}
	
	
	private void loadBinStock(){
		String url = Statics.URL_2 + Statics.URL_BinStock + ncode
				+ "&field=ZG,ZD,ZX,ZSP";
		Log.v(TAG, "URL_BinStock="+url);
		StringRequest strRequest = new StringRequest(url, new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				try {
					Log.v(TAG, "URL_BinStock="+response);
					if(response!=null){
						String[] rs = response.split(";");
						int length = rs.length;
						for(int i =0;i< length; i++ ){ 
							String[] result = rs[i].split(",");
							ChooseStock stockInfo = mDatas.get(i);  
							stockInfo.zx = (result[4].trim());
							
							stockInfo.zsp = (result[5].trim());
							if(Float.parseFloat(stockInfo.zx)==0){
								stockInfo.zx = stockInfo.zsp;
							}
							 String zdl = KouFuTools.df2.format ( (Float.parseFloat(stockInfo.zx) - Float.parseFloat(stockInfo.zsp)) / Float.parseFloat(stockInfo.zsp) * 100 ) +"%";
							 stockInfo.ztl = zdl;
						}
					} 
					mAdapter.datas = mDatas;
					mAdapter.notifyDataSetChanged();
					mPullToRefreshListView.onRefreshComplete();
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				Log.e(TAG, error.getMessage(), error);
				mPullToRefreshListView.onRefreshComplete();
			}
		});
		strRequest.setCharset("GBK");
		strRequest.setTag(TAG);
		RequestQueueSingleton.getInstance(context).addToRequestQueue(strRequest);
	}
	private OnItemClickListener itemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {  
			ChooseStock tu = mDatas.get(position-1);
			Intent intent = new Intent(MyChooseStockActivity.this,MarketDeatilActivity.class);
			intent.putExtra("stockCode", tu.stockcode);
			intent.putExtra("stockName", tu.stockname);
			intent.putExtra("inZixuangu", "yes");
			startActivity(intent);
		}
	};

	@Override
	public boolean handleMessage(Message msg) { 
		switch (msg.what) {
		case 3:
			mPullToRefreshListView.setRefreshing(true);
			break;

		default:
			break;
		}
		return false;
	}
	
	
	@Override
	protected void onStop() { 
		super.onStop();
		RequestQueueSingleton.getInstance(context).cancleAllReq(TAG);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		 switch (v.getId()) {
		case R.id.img_callback:
			this.finish();
			break;

		default:
			break;
		}
		
	}
}
